package com.lct.todo.daofactory;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DaoFactory {
    private static final String DRIVER = "com.mysql.jdbc.Driver";
    private static final String URL = "jdbc:mysql://127.0.0.1:3306/todo";
    private static final String USER = "root";
    private static final String PWD = "root";
    private static Connection con = null;
    private static PreparedStatement pstmt = null;
    private static ResultSet rs = null;
    private static int rows = 0;

    /**
     * 连接数据库
     *
     * @return 连接对象
     */
    private static Connection getCon() {
        try {
            Class.forName(DRIVER);
            con = DriverManager.getConnection(URL, USER, PWD);
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        return con;
    }

    /**
     * 更新，删除，插入
     *
     * @param sql   SQL语句
     * @param paras 参数
     * @return 执行结果
     */
    public static int exeUp(String sql, String[] paras) {
        con = getCon();
        try {
            pstmt = con.prepareStatement(sql);
            if (paras != null)
                for (int i = 0; i < paras.length; i++) {
                    pstmt.setString(i + 1, paras[i]);
                }
            rows = pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        closeAll();
        return rows;
    }

    /**
     * 查询
     *
     * @param sql   SQL语句
     * @param paras 参数
     * @return 执行结果
     */
    public static ResultSet exeQu(String sql, String[] paras) {
        con = getCon();
        try {
            pstmt = con.prepareStatement(sql);
            if (paras != null)
                for (int i = 0; i < paras.length; i++) {
                    pstmt.setString(i + 1, paras[i]);
                }
            rs = pstmt.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }

    /**
     * 关闭链接
     */
    public static void closeAll() {
        try {
            if (con != null)
                con.close();
            if (pstmt != null)
                pstmt.close();
            if (rs != null)
                rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
